<template>
  <div class="app-container">
    <div class="app-card">
      <!-- 搜索和工具栏 -->
      <div class="table-toolbar">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-form-item label="分类名称">
            <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable size="small" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        
        <div>
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
        </div>
      </div>
      
      <!-- 表格 -->
      <el-table v-loading="loading" :data="categoryList" border>
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="name" label="分类名称" min-width="150" />
        <el-table-column prop="sort" label="排序" width="100" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.current"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategories, addCategory, updateCategory, deleteCategory } from '@/api/category'

export default {
  name: 'Category',
  data() {
    return {
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: ''
      },
      // 总记录数
      total: 0,
      // 分类列表
      categoryList: [],
      // 加载状态
      loading: false,
      // 对话框标题
      dialogTitle: '',
      // 对话框显示状态
      dialogVisible: false,
      // 表单对象
      form: {
        id: undefined,
        name: '',
        sort: 0
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取分类列表
    getList() {
      this.loading = true
      listCategories({
        current: this.queryParams.current,
        size: this.queryParams.size,
        name: this.queryParams.name
      }).then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.categoryList = response
          this.total = response.length
        } else {
          // 否则尝试获取list和total字段
          this.categoryList = response.list || response.records || []
          this.total = response.total || 0
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 搜索按钮点击事件
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    // 重置按钮点击事件
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams.name = ''
      this.queryParams.current = 1
      this.getList()
    },
    // 每页数量改变事件
    handleSizeChange(val) {
      this.queryParams.size = val
      this.getList()
    },
    // 页码改变事件
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    // 添加按钮点击事件
    handleAdd() {
      this.dialogTitle = '添加分类'
      this.form = {
        id: undefined,
        name: '',
        sort: 0
      }
      this.dialogVisible = true
    },
    // 编辑按钮点击事件
    handleUpdate(row) {
      this.dialogTitle = '编辑分类'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 删除按钮点击事件
    handleDelete(row) {
      this.$confirm('确认删除该分类吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCategory(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // 表单提交事件
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateCategory(this.form).then(() => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            addCategory(this.form).then(() => {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style> 